#include "UISlider.h"
#include "UIButton.h"
#include "../../Input/Mouse.h"

UISlider::UISlider()
{
	Position = Point{ 80, 80 };
	Width = 140;
	Height = 4;
	KnobRadius = 8;
	SetupSliderKnob();
}

UISlider::UISlider(float x, float y) : UIElement(x, y)
{
	Width = 140;
	Height = 4;
	KnobRadius = 6;
	SetupSliderKnob();
}

UISlider::UISlider(float x, float y, float width, float height) : UIElement(x, y, width, height)
{
	KnobRadius = 8;
	SetupSliderKnob();
}

UISlider::UISlider(float x, float y, float width, float height, float knobRadius) : UIElement(x, y, width, height)
{
	KnobRadius = knobRadius;
	SetupSliderKnob();
}

void UISlider::SetupSliderKnob()
{
	SliderKnob = std::unique_ptr<UIButton>(new UIButton(Position.x + Width / 2, Position.y + Height / 2, KnobRadius * 2, KnobRadius * 2, "", "", 1, Color::White, true, KnobRadius, KnobRadius));
	SliderKnob->BorderStroke = 0;

	SliderKnob->AddLeftMouseClickEvent([this](UIElement* sender) {
		std::thread temp_thread([this, sender]() {
			while (GetAsyncKeyState(VK_LBUTTON) & 0x8000)
			{
				sender->Position.x = Mouse::GetMousePosX(SourceWindow) - KnobRadius;

				// Correction phase
				if (sender->Position.x > Position.x + Width)
					sender->Position.x = Position.x + Width;
				else if (sender->Position.x < Position.x)
					sender->Position.x = Position.x;

				float percentage = ((sender->Position.x - Position.x) / Width);
				float precise_value = percentage * MaxValue;
				Value = roundf(precise_value / Interval) * Interval;

				sender->Position.x = Position.x + Width * (Value / MaxValue);
			}
		});
		temp_thread.detach();
	});
}

void __stdcall UISlider::Draw(Graphics* graphics)
{
	if (Value > MaxValue) Value = MaxValue;
	if (Value < MinValue) Value = MinValue;
	
	if (SliderKnob->Position.x > Position.x + Width)
		SliderKnob->Position.x = Position.x + Width;
	else if (SliderKnob->Position.x < Position.x)
		SliderKnob->Position.x = Position.x;

	SliderKnob->Position.y = Position.y + (Height / 2) - KnobRadius;
	SliderKnob->HoverOnColor = HoverOnColor;

	if (Value != m_PreviousValue)
		for (progress_callback_function cb : m_ProgressCallbacks)
			cb(this);

	m_PreviousValue = GetRoundedValue();

	// draw a bar
	graphics->DrawRectangle(Position.x, Position.y, Width, Height, color.r, color.g, color.b, color.a, 2, true);

	SliderKnob->Draw(graphics);
}

UIElement* UISlider::_get_slider_knob_handle_()
{
	return SliderKnob.get();
}
